import constants from './constants'

export default {
	calculateAspectRatioFit: function (srcWidth, srcHeight, maxWidth, maxHeight) {
		// resize our image into the specs we need

		let ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight)

		return { width: srcWidth * ratio, height: srcHeight * ratio }
	},

	radians: function (degrees) {
		// convert our rotation information into radians for canvas manipulation

		return (degrees * Math.PI) / 180
	},

	rotateCoordinate(cx, cy, x, y, angle) {
		// rotate the landmarks provided by the cloud vision API if the face in the supplied
		// image isn't vertically aligned

		var radians = (Math.PI / 180) * angle,
			cos = Math.cos(radians),
			sin = Math.sin(radians),
			nx = cos * (x - cx) + sin * (y - cy) + cx,
			ny = cos * (y - cy) - sin * (x - cx) + cy
		return [nx, ny]
	},

	rotateCanvas: function (workingCanvas, rollAngle) {
		let canvas = document.createElement('canvas')
		canvas.width = workingCanvas.width
		canvas.height = workingCanvas.height
		let ctx = canvas.getContext('2d')

		ctx.save() //saves the state of canvas
		ctx.clearRect(0, 0, workingCanvas.width, workingCanvas.height) //clear the canvas
		ctx.translate(workingCanvas.width / 2, workingCanvas.height / 2) //let's translate
		ctx.rotate((Math.PI / 180) * -rollAngle) //increment the angle and rotate the image
		ctx.translate(-(workingCanvas.width / 2), -(workingCanvas.height / 2)) //let's translate
		ctx.drawImage(
			workingCanvas,
			workingCanvas.width / 2 - workingCanvas.width / 2,
			workingCanvas.height / 2 - workingCanvas.height / 2,
			workingCanvas.width,
			workingCanvas.height
		) //draw the image ;)
		ctx.restore() //restore the state of canvas

		return canvas
	},

	getRollAngle(cx, cy, ex, ey) {
		var dy = ey - cy
		var dx = ex - cx
		var theta = Math.atan2(dy, dx) // range (-PI, PI]
		theta *= 180 / Math.PI // rads to degs, range (-180, 180]
		//if (theta < 0) theta = 360 + theta; // range [0, 360)
		return theta
	},
}
